#include "pagewidgetmini.h"

#include "../../uitools/vhc/constview4fun.h"
#include "../../uitools/vhc/constview4id.h"

#include <QPainter>
#include <QStyleOption>
#include <QListView>
#include <QKeyEvent>

#include <QTime>
#include <QTimer>
#include <QDebug>

#define MINIMUM_PAGE 1




//q:303103757 and v:qt5_qt6

/***
 * 如何使用
 * Pagination必须基于一个QWidget创建，否则会引发错误。

PageWidgetMini* pa = new PageWidgetMini(QWidget*);
设置总页数
Pagination需要设置一个总的页数，来初始化页码。

pa->SetTotalItem(count);
设置可选的每页数量
可以通过传给Pagination一个整形数组，来设置每页显示的条目数。

int args[4] = {1, 100, 200, 300};
pa->SetItemPerPage(args, 4);
刷新配置参数
当上面参数设置完成后，需要调用一次Refresh来刷新配置。

pa->Refresh();
获取当前页数的变化
当Pagination当前的页码发生变化时，会产生一个PageChanged信号，原型如下：

void GotoPageSignals(int nPage);
其中，nPage代表要跳转的页数。

获取每页条目数的变化
当Pagination的每页数量发生变化时，会产生一个NumberPerPageChanged信号，原型如下：

void NumberPerPageChanged(int nCount);
其中，nCount表示最新的每页条目数量。
***/

namespace kepen {
namespace core {

PageWidgetMini::PageWidgetMini(QWidget *parent) :
    QWidget(parent),
    m_nCurrentPage(MINIMUM_PAGE),
    m_nMaxPage(MINIMUM_PAGE)

{
    Init();
    // QTimer::singleShot(400,this,SLOT(ClearPage()));
}

PageWidgetMini::~PageWidgetMini()
{


}

void PageWidgetMini::keyPressEvent(QKeyEvent *event)
{
    int k= event->key();
    if(Qt::Key_PageUp == k ||Qt::Key_PageDown == k)
    {

        keyPress4Page(k);
        return;
    }
    QWidget::keyPressEvent(event);
}

void PageWidgetMini::SetTotalItem(int nTotal)
{

    int nSizePage = m_pItemEachPage->GetSizePage();
    if(nSizePage > 0)
    {
        m_nMaxPage = nTotal / nSizePage;
        if(nTotal % nSizePage > 0) ++m_nMaxPage;
        if(m_nMaxPage <= 0) m_nMaxPage = MINIMUM_PAGE;

    }else{
        m_nMaxPage = MINIMUM_PAGE;
    }
    m_pTotalItem->SetTotal(nTotal,m_nMaxPage);
    Reload();
}

int PageWidgetMini::getSizePage() const
{
    int nSizePage = m_pItemEachPage->GetSizePage();
    return nSizePage;
}

int PageWidgetMini::getCurrPage() const
{
    return m_nCurrentPage;
}

int PageWidgetMini::getMaxPage() const
{
    return m_nMaxPage;
}

void PageWidgetMini::setCurrentPage(int page)
{
    if(page > 0 && page <= m_nMaxPage && m_nCurrentPage != page){
        m_nCurrentPage = page;
        m_pGotoItem->setCurrentPage(page);
    }
}

void PageWidgetMini::SetItemPerPage(int *args, int size)
{
    m_pItemEachPage->SetSizePageData(args, size);
    int EachPage = m_pItemEachPage->GetSizePage();
    if(EachPage > 0)
    {
        int nTotal = m_pTotalItem->GetTotal();
        m_nMaxPage = nTotal / EachPage;
        if(nTotal % EachPage > 0) ++m_nMaxPage;
        if(m_nMaxPage <= 0) m_nMaxPage = MINIMUM_PAGE;

    }
}

void PageWidgetMini::Refresh()
{
    Reload();
}

void PageWidgetMini::ChangeView(int currentPage)
{
    if(m_nMaxPage<=1){
        m_pBtnFirst->setDisabled(false);
        m_pBtnLeft->setDisabled(false);
        m_pBtnRight->setDisabled(false);
        m_pBtnLast->setDisabled(false);
    }
    else
    {
        if(currentPage == MINIMUM_PAGE)
        {
            // 当前第一页，禁用左按钮
            m_pBtnFirst->setDisabled(true);
            m_pBtnLeft->setDisabled(true);
        }
        else
        {
            // 开启右按钮
            m_pBtnFirst->setDisabled(false);
            m_pBtnLeft->setDisabled(false);
        }
        if(currentPage == m_nMaxPage)
        {
            // 最后一页，禁用右按钮
            m_pBtnRight->setDisabled(true);
            m_pBtnLast->setDisabled(true);
        }
        else
        {
            // 开启左按钮
            m_pBtnRight->setDisabled(false);
            m_pBtnLast->setDisabled(false);
        }

    }

    m_pGotoItem->setCurrentPage(currentPage);
}



void PageWidgetMini::Init()
{
    int heightThiz = 36;
    QString nameThiz("PageWidgetMini");//transparent
    QString cssThiz = QString("QWidget#%1{background-color:transparent;font-size:%2px;}").arg(nameThiz).arg(TextSize_ToolBar);
    setObjectName(nameThiz);
    setStyleSheet(cssThiz);

    setAutoFillBackground(true);
    setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
    setMinimumSize(600, heightThiz);
    setContentsMargins(0,0,0,0);


    m_pHMainLayout = new QHBoxLayout(this);
    m_pHMainLayout->setContentsMargins(0,0,0,0);
    m_pHMainLayout->setSpacing(0);

    m_pTotalItem = new TotalItem(this);
    m_pTotalItem->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
    m_pTotalItem->setFixedHeight(heightThiz);
    m_pItemEachPage = new SizePageCombox(this);

    m_pGotoItem = new GotoPageInput(this);
    m_pGotoItem->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
    m_pGotoItem->setFixedHeight(heightThiz);

    m_pBtnFirst = new QPushButton(QStringLiteral("首页"), this);
    m_pBtnLeft = new QPushButton(QStringLiteral("前页"), this);
    m_pBtnRight = new QPushButton(QStringLiteral("后页"), this);
    m_pBtnLast = new QPushButton(QStringLiteral("尾页"), this);


    QString cssBtn = QString::asprintf("QPushButton{background-color:transparent;color:#323232;padding:4px;border:0px;font-size:%dpx;}"
                                       "QPushButton:hover{background-color:#%08x;color:black;}QPushButton:pressed{background-color: #%08x;}"
                                       "QPushButton::disabled{color:#%08x;}"
                                       ,TextSize_ToolBar,Background_BtnOver,Background_BtnDown,Color_Btn_Disabled);
    m_pBtnFirst->setStyleSheet(cssBtn);
    m_pBtnRight->setStyleSheet(cssBtn);
    m_pBtnLeft->setStyleSheet(cssBtn);
    m_pBtnLast->setStyleSheet(cssBtn);

    // m_pBtnOmitFront->setStyleSheet(QStringLiteral("QPushButton{border:none;background-color:transparent;background:background-position:center;}"
    //                                               "QPushButton:hover{{background-color:white;color:black;background-position:center;}"));
    // m_pBtnOmitBack->setStyleSheet(QStringLiteral("QPushButton{border:none;background-color:transparent;background-position:center;}"
    //                                              "QPushButton:hover{background:background-color:white;color:black;background-position:center;}"));
    m_nCurrentPage = 1;
    int args[4] = { 10, 20, 30, 100 };
    SetItemPerPage(args, sizeof (args) / sizeof (int));






    ChangeView(m_nCurrentPage);

    m_pHMainLayout->addWidget(m_pItemEachPage);
    m_pHMainLayout->addWidget(m_pTotalItem ,0, Qt::AlignLeft );
    m_pHMainLayout->addSpacerItem(new QSpacerItem(6,heightThiz, QSizePolicy::Fixed, QSizePolicy::Policy::Fixed));

    m_pHMainLayout->addWidget(m_pBtnFirst);
    m_pHMainLayout->addWidget(m_pBtnLeft);

    m_pHMainLayout->addWidget(m_pGotoItem);

    m_pHMainLayout->addWidget(m_pBtnRight);
    m_pHMainLayout->addWidget(m_pBtnLast);


    m_pHMainLayout->addStretch();


    connect(m_pBtnFirst, &QPushButton::clicked, this, [this](){
        m_nCurrentPage = 1;

        ChangeView(m_nCurrentPage);
        Q_EMIT GotoPageSignals(m_nCurrentPage);
    });
    // 上一页
    connect(m_pBtnLeft, &QPushButton::clicked, this, [this](){
        if(m_nCurrentPage - 1 < 0) m_nCurrentPage = 1;
        else --m_nCurrentPage;
        ChangeView(m_nCurrentPage);
        Q_EMIT GotoPageSignals(m_nCurrentPage);
    });

    // 下一页
    connect(m_pBtnRight, &QPushButton::clicked, this, [&](){
        if(m_nCurrentPage + 1 > m_nMaxPage) m_nCurrentPage = m_nMaxPage;
        else ++m_nCurrentPage;
        ChangeView(m_nCurrentPage);
        Q_EMIT GotoPageSignals(m_nCurrentPage);
    });

    connect(m_pBtnLast, &QPushButton::clicked, this, [&](){
        m_nCurrentPage = m_nMaxPage;

        ChangeView(m_nCurrentPage);
        Q_EMIT GotoPageSignals(m_nCurrentPage);
    });


    // 前往第N页
    connect(m_pGotoItem, &GotoPageInput::GotoPage, this, [&](int nPage){
        if(nPage > m_nMaxPage) nPage = m_nMaxPage;
        if(nPage < MINIMUM_PAGE) nPage = MINIMUM_PAGE;
        if(nPage + 1 > m_nMaxPage) m_nCurrentPage = m_nMaxPage;
        else m_nCurrentPage = nPage;
        ChangeView(m_nCurrentPage);
        Q_EMIT GotoPageSignals(m_nCurrentPage);
    });

    // 每页条码变化
    connect(m_pItemEachPage, &SizePageCombox::EachPageItemChanged, this, [&](int nCount){
        int EachPage = m_pItemEachPage->GetSizePage();
        if(EachPage > 0)
        {
            int nTotal = m_pTotalItem->GetTotal();
            m_nMaxPage = nTotal / EachPage;
            if(nTotal % EachPage > 0)
                ++m_nMaxPage;
            if(m_nMaxPage <= 0)
                m_nMaxPage = MINIMUM_PAGE;
            // 如果m_nMaxPage小于MAX_BUTTON_COUNT，则不变。


        }
        Reload();
        //  Q_EMIT NumberPerPageChanged(nCount,m_nCurrentPage);
        Q_EMIT GotoPageSignals(m_nCurrentPage);
    });
}

void PageWidgetMini::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
    QWidget::paintEvent(event);
}





void PageWidgetMini::Reload()
{

    int lastPage = m_nCurrentPage;
    m_nCurrentPage = 1;


    // 初始化一次界面
    ChangeView(m_nCurrentPage);

    if(lastPage > m_nMaxPage) // 上次停留的页数大于现在的最大页数
        m_nCurrentPage = m_nMaxPage; // 直接变成当前最大页数
    else
        m_nCurrentPage = lastPage; // 否则还是保持当前页数
    ChangeView(m_nCurrentPage); // 再次刷新下当前界面


}

void PageWidgetMini::keyPress4Page(int key)
{
    int p = m_nCurrentPage,m=m_nMaxPage;

    if(Qt::Key_PageUp == key && p > 1)
        --p;
    else if(Qt::Key_PageDown == key && p < m)
        ++p;
    else p = -1;

    if(p>0)
    {
        m_pGotoItem->setCurrentPage(p);
        m_nCurrentPage = p;

        Q_EMIT GotoPageSignals(p);

    }

}

void PageWidgetMini::clearPage()
{
    QWidget* tmp;
    QLayoutItem* item;
    QSpacerItem *itemSpace;
    QHBoxLayout* lay = this->m_pHMainLayout;
    int count = lay->count();

    for(int i = 0; i < count; i++)
    {


        if((item = lay->takeAt(0)))
        {
            if((tmp = item->widget()))
            {
                // lay->removeWidget(tmp);
                delete tmp;
                tmp = nullptr;
            }else{

                if((itemSpace = item->spacerItem())){
                    // lay->removeItem(item);
                    //不能调用  delete itemSpace，系统直接报错，崩溃
                    // delete itemSpace;
                    // itemSpace = nullptr;
                    qDebug() << __FILE__ << __LINE__ << "~ is spacerItem ****-----:" << i;

                    qDebug() << __FILE__ << __LINE__ << "~spacerItem";
                }
            }

            delete item;
            item = nullptr;

        }

    }
}

void PageWidgetMini::ClearChildrenImpl()
{
    QHBoxLayout* layout = this->m_pHMainLayout;
    QLayoutItem *child;
    QWidget *tmp;
    while ((child = layout->takeAt(0)) != nullptr)
    {
        if((tmp = child->widget()) && tmp != nullptr)
        {
            delete child->widget();
        }

        delete child;
    }
}



}
}
